#!/bin/bash
#these were originally in the retired script /sbin/pup_event_frontend_d
#130610 bugfix remove desktop icon if label different from drv name.
#130613 npierce: rox_free_coords() supports screen widths not multiple of 32.
#130807 L18L: set executable in Woof 'VCSMETEDATA' file. move gettext declaration from other scripts.

BPS=`busybox ps`

echo "$BPS" | grep -q 'ROX-Filer -p' && {
	ROX_DESKTOP=yes
}

. /etc/rc.d/functions_x #fx_* functions

#130807 L18L
export TEXTDOMAIN=pup_event_frontend_d
export OUTPUT_CHARSET=UTF-8
. gettext.sh

#set -x

#===================================================================
# precaution

if [ -z "$DISPLAY" ] ; then
	[ -f /tmp/services/x_display ] && . /tmp/services/x_display
	export DISPLAY
fi

if [ "$USER_ID" = "" ] ; then
	[ -f /tmp/services/user_info ] && . /tmp/services/user_info
	export PATH HOME LANG USER
fi

#===================================================================

roxfiler_R() {
	if [ "$USER" = "root" -o "$USER" = "" ] ; then
		roxfiler -R
	else
		su $USER -c 'roxfiler -R'
	fi
}

# $1: dev
# create /tmp/pup_event_frontend/drive_${dev}/AppRun
drive_all_frontend() { # $1: devname
	local dev=$1
	if [ ! -d /tmp/pup_event_frontend/drive_${dev} ] ; then
		mkdir -p /tmp/pup_event_frontend/drive_${dev}
	fi
	cat > /tmp/pup_event_frontend/drive_${dev}/AppRun <<EOF
#!/bin/sh
exec /usr/local/pup_event/drive_all $dev \$@
EOF
	chmod +x /tmp/pup_event_frontend/drive_${dev}/AppRun
}

#===================================================================

rox_icon_unmounted_func() {
	[ "$ROX_DESKTOP" != "yes" ] && return
	#passed params: drivename category  ex: sda usbdrv
	DRVICON="drive48.png" #default.
	[ "$2" = "usbdrv" ] && DRVICON="usbdrv48.png"
	[ "$2" = "card" ] && DRVICON="card48.png"
	[ "$2" = "floppy" ] && DRVICON="floppy48.png"
	[ "$2" = "optical" ] && DRVICON="optical48.png"
	[ "$3" = "crypto_LUKS" ] && DRVICON="lock-screen48.png"
	#find out if already done...
	if [ -f /root/.config/rox.sourceforge.net/ROX-Filer/globicons ];then
		GLOBLINES="`cat /root/.config/rox.sourceforge.net/ROX-Filer/globicons | tr '\n' '|' | sed -e 's%</rule>|%\n%g'`"
		diPATTERN='/tmp/pup_event_frontend/drive_'"${1}"'"'
		[ "`echo "$GLOBLINES" | grep "$diPATTERN" | grep "$DRVICON"`" != "" ] && return
	fi
	#-
	echo "<?xml version=\"1.0\"?>
<env:Envelope xmlns:env=\"http://www.w3.org/2001/12/soap-envelope\">
 <env:Body xmlns=\"http://rox.sourceforge.net/SOAP/ROX-Filer\">
  <SetIcon>
   <Path>/tmp/pup_event_frontend/drive_${1}</Path>
   <Icon>/usr/local/lib/X11/pixmaps/${DRVICON}</Icon>
  </SetIcon>
 </env:Body>
</env:Envelope>"  | roxfiler_R
}

rox_icon_mounted_func() {
	[ "$ROX_DESKTOP" != "yes" ] && return
	#passed params: drivename category  ex: sda usbdrv
	DRVICON="drive_mntd48.png" #default.
	[ "$2" = "usbdrv" ] && DRVICON="usbdrv_mntd48.png"
	[ "$2" = "card" ] && DRVICON="card_mntd48.png"
	[ "$2" = "floppy" ] && DRVICON="floppy_mntd48.png"
	[ "$2" = "optical" ] && DRVICON="optical_mntd48.png"
	imPATTERN="^/dev/${1} |^/dev/mapper/lukspartition_${1} " #support luks-encrypted partitions
	if [ "`mount | grep -E "$imPATTERN" | cut -f 1,3 -d ' ' | grep -v ' /initrd/' | grep -v ' /$'`" = "" ];then
		#only partitions mntd on /initrd/* then must be mntd at boot. cannot unmount.
		#also, full hd install has partition mntd on '/'.
		DRVICON="drive_mntd_boot48.png" #default.
		[ "$2" = "usbdrv" ] && DRVICON="usbdrv_mntd_boot48.png"
		[ "$2" = "card" ] && DRVICON="card_mntd_boot48.png"
		[ "$2" = "floppy" ] && DRVICON="floppy_mntd_boot48.png"
		[ "$2" = "optical" ] && DRVICON="optical_mntd_boot48.png"
	fi
	#find out if already done...
	if [ -f /root/.config/rox.sourceforge.net/ROX-Filer/globicons ];then
		GLOBLINES="`cat /root/.config/rox.sourceforge.net/ROX-Filer/globicons | tr '\n' '|' | sed -e 's%</rule>|%\n%g'`"
		diPATTERN='/tmp/pup_event_frontend/drive_'"${1}"'"'
		[ "`echo "$GLOBLINES" | grep "$diPATTERN" | grep "$DRVICON"`" != "" ] && return
	fi
	echo "<?xml version=\"1.0\"?>
<env:Envelope xmlns:env=\"http://www.w3.org/2001/12/soap-envelope\">
 <env:Body xmlns=\"http://rox.sourceforge.net/SOAP/ROX-Filer\">
  <SetIcon>
   <Path>/tmp/pup_event_frontend/drive_${1}</Path>
   <Icon>/usr/local/lib/X11/pixmaps/${DRVICON}</Icon>
  </SetIcon>
 </env:Body>
</env:Envelope>"  | roxfiler_R
}
#------------------------------------------------------------

rox_create_appinfo_func() { #needs INFO, DRV_CATEGORY, MOREITEMS, ONEDRVNAME
	echo "<?xml version=\"1.0\"?>
<AppInfo>
  <Summary>${INFO}</Summary>
  <About>
   <Purpose>`gettext \"Drive icons are part of Puppy Event Manager, see System menu\"`</Purpose>
   <Authors>Barry Kauler LGPL 2008</Authors>
  </About>
  <AppMenu>
   <Item option=\"pmount_${DRV_CATEGORY}\" icon=\"gtk-harddisk\"><Label>$(gettext 'Run Pmount Puppy Drive Mounter')</Label></Item><Item option=\"eventmanager\" icon=\"gtk-execute\"><Label>$(gettext 'Run Desktop Drive Icon Manager')</Label></Item>${MOREITEMS}
  </AppMenu>
</AppInfo>" > /tmp/pup_event_frontend/drive_${ONEDRVNAME}/AppInfo.xml
}

rox_free_coord() {
	#find a free place on desktop. v410 avoid exact overlapping icons...
	#091208 finetune placement, also any side of screen...
	#read the coords grid, code from shinobar...
	if [ -z "$SCRN_X" -o -z "$SCRN_Y" ] ; then
		while read a b c ; do
			case $a in -geometry)
				#1366x768+0+0
				SCRNXY=${b%%+*} #1366x768
				read SCRN_X SCRN_Y <<< "${SCRNXY//x/ }"
				break
				;;
			esac
		done <<< "$(LANG=C xwininfo -root)"
	fi
	#echo $SCRN_X $SCRN_Y #DEBUG
	COORDSGRID="`grep -o ' x="[0-9]*" y="[0-9]*" ' /root/Choices/ROX-Filer/PuppyPin | sed 's/[0-9]"/"/g'`"
	PIN_GRID_STEP=`grep "pinboard_grid_step" /root/.config/rox.sourceforge.net/ROX-Filer/Options | sed -e "s/ *<[^>]*>//g"`
	[ ! $PIN_GRID_STEP ] && PIN_GRID_STEP=16 #16=medium.
	[ $PIN_GRID_STEP -eq 0 ] && PIN_GRID_STEP=16 #precaution.
	PIN_GRID_STEP2=$(($PIN_GRID_STEP / 2))
	MAX_X=$(( $SCRN_X - 96 ))
	MAX_Y=$(( $SCRN_Y - 96 ))
	#echo "MAX_X: $MAX_X MAX_Y: $MAX_Y" #DEBUG
	case $ICON_PLACE_ORIENTATION in #see /etc/eventmanager
	bottom)
		COORD_Y=$(( $SCRN_Y - $ICON_PLACE_EDGE_GAP )) #default 64, see /etc/eventmanager
		COORD_Y=$(( ( $COORD_Y + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP * $PIN_GRID_STEP ))
		COORD_X=$ICON_PLACE_START_GAP #default 32, see /etc/eventmanager
		COORD_X=$(( ( $COORD_X + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP *  $PIN_GRID_STEP )) #130613
		xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
		#echo "$xPATTERN" #DEBUG
		xyCNT=0 #precaution.
		while [ 1 ];do
			xgPATTERN="${xPATTERN//[0-9]\"/\"}" #="`echo -n "$xPATTERN" | sed 's/[0-9]"/"/g'`"
			#echo "* $xgPATTERN" #DEBUG
			[ "`echo "$COORDSGRID" | grep -E "$xgPATTERN"`" = "" ] && break
			COORD_X=$(( $COORD_X + $ICON_PLACE_SPACING ))
			if [ $COORD_X -gt $MAX_X ];then #start next line up.
				xyCNT=$(( $xyCNT + 1 ))
				[ $xyCNT -gt 1 ] && break
				COORD_Y=$(( $COORD_Y - $ICON_PLACE_SPACING ))
				COORD_X=$ICON_PLACE_START_GAP
			fi
			xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
			#echo "$xPATTERN" #DEBUG
		done
	;;
	top)
		COORD_Y=$ICON_PLACE_EDGE_GAP
		COORD_Y=$(( ( $COORD_Y + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP * $PIN_GRID_STEP ))
		COORD_X=$ICON_PLACE_START_GAP #default 32, see /etc/eventmanager
		COORD_X=$(( ( $COORD_X + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP * $PIN_GRID_STEP )) #130613
		xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
		xyCNT=0 #precaution.
		while [ 1 ];do
			xgPATTERN="${xPATTERN//[0-9]\"/\"}" #="`echo -n "$xPATTERN" | sed 's/[0-9]"/"/g'`"
			[ "`echo "$COORDSGRID" | grep -E "$xgPATTERN"`" = "" ] && break
			COORD_X=$(( $COORD_X + $ICON_PLACE_SPACING ))
			if [ $COORD_X -gt $MAX_X ];then #start next line down.
				xyCNT=$(( $xyCNT + 1 ))
				[ $xyCNT -gt 1 ] && break
				COORD_Y=$(( $COORD_Y + $ICON_PLACE_SPACING ))
				COORD_X=$ICON_PLACE_START_GAP
			fi
			xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
		done
	;;
	left)
		COORD_X=$ICON_PLACE_EDGE_GAP #default 64, see /etc/eventmanager
		COORD_X=$(( ( $COORD_X + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP * $PIN_GRID_STEP )) #130613
		COORD_Y=$ICON_PLACE_START_GAP #default 32, see /etc/eventmanager
		COORD_Y=$(( ( $COORD_Y + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP *  $PIN_GRID_STEP ))
		xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
		xyCNT=0 #precaution.
		while [ 1 ];do
			xgPATTERN="${xPATTERN//[0-9]\"/\"}" #="`echo -n "$xPATTERN" | sed 's/[0-9]"/"/g'`"
			[ "`echo "$COORDSGRID" | grep -E "$xgPATTERN"`" = "" ] && break
			COORD_Y=$(( $COORD_Y + $ICON_PLACE_SPACING ))
			if [ $COORD_Y -gt $MAX_Y ];then #start next row.
				xyCNT=$(( $xyCNT + 1 ))
				[ $xyCNT -gt 1 ] && break
				COORD_X=$(( $COORD_X + $ICON_PLACE_SPACING ))
				COORD_Y=$ICON_PLACE_START_GAP
			fi
			xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
		done
	;;
	right)
		COORD_X=$(( $SCRN_X - $ICON_PLACE_EDGE_GAP )) #default 64, see /etc/eventmanager
		COORD_X=$(( ( $COORD_X + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP * $PIN_GRID_STEP )) #130613
		COORD_Y=$ICON_PLACE_START_GAP #default 32, see /etc/eventmanager
		COORD_Y=$(( ( $COORD_Y + $PIN_GRID_STEP2 ) / $PIN_GRID_STEP * $PIN_GRID_STEP ))
		xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
		xyCNT=0 #precaution.
		while [ 1 ];do
			xgPATTERN="${xPATTERN//[0-9]\"/\"}" #="`echo -n "$xPATTERN" | sed 's/[0-9]"/"/g'`"
			[ "`echo "$COORDSGRID" | grep -E "$xgPATTERN"`" = "" ] && break
			COORD_Y=$(( $COORD_Y + $ICON_PLACE_SPACING ))
			if [ $COORD_Y -gt $MAX_Y ];then #start next row back.
				xyCNT=$(( $xyCNT + 1 ))
				[ $xyCNT -gt 1 ] && break
				COORD_X=$(( $COORD_X - $ICON_PLACE_SPACING ))
				COORD_Y=$ICON_PLACE_START_GAP
			fi
			xPATTERN=" x=\"${COORD_X}\" y=\"${COORD_Y}\" | x=\"$((COORD_X + 1))\" y=\"$((COORD_Y + 1))\" "
		done
	;;
	esac
	#echo "$ICON_PLACE_ORIENTATION : $COORD_X $COORD_Y" #DEBUG
}

rox_add_pinboard_func() { #needs ONEDRVNAME, DRV_CATEGORY, FSTYPE
	[ "$ROX_DESKTOP" != "yes" ] && return
	#v411 rerwin: avoid icon getting duplicated if it is renamed...
	ppPATTERN="/tmp/pup_event_frontend/drive_${ONEDRVNAME}<"
	grep -q "$ppPATTERN" /root/Choices/ROX-Filer/PuppyPin && return #precaution.
	rox_free_coord
	#120503 the label "mmcblk0p1" (SD memory cards via mmc interface) is too long...
	cutONEDRVNAME=${ONEDRVNAME//cblk/} #mmcblk0p1 -> mm0p1
	if [ "$LABELPARTITIONS" = "true" ] ; then
		if [ "$DRV_LABEL" ] ; then
			[ "${#DRV_LABEL}" -gt 8 ] && DRV_LABEL="${DRV_LABEL:0:7}.."
			cutONEDRVNAME="${cutONEDRVNAME}
${DRV_LABEL}"
		fi
	fi
	echo "<?xml version=\"1.0\"?>
<env:Envelope xmlns:env=\"http://www.w3.org/2001/12/soap-envelope\">
 <env:Body xmlns=\"http://rox.sourceforge.net/SOAP/ROX-Filer\">
  <PinboardAdd>
   <Path>/tmp/pup_event_frontend/drive_${ONEDRVNAME}</Path>
   <X>${COORD_X}</X>
   <Y>${COORD_Y}</Y>
   <Label>${cutONEDRVNAME}</Label>
   <Args>${DRV_CATEGORY} ${FSTYPE}</Args>
  </PinboardAdd>
 </env:Body>
</env:Envelope>"  | roxfiler_R
}

create_icon_func() {
	[ "$ICONDESK" = "false" ] && "$ICONPARTITIONS" = "false"
	#create desktop icon, and directory with handler script, icon and help...
	#requires global variables DRV_NAME, DRV_CATEGORY, DRV_DESCRIPTION.

	#-- PARTITIONS - $PROBEPART
	if [ "$HOTPLUGON" = "true" -a "$ICONPARTITIONS" = "true" ] ; then
		# $PROBEPART already known - was set in frontend_startup/change
		DRVINFO="`echo "$PROBEPART" | grep "^/dev/${DRV_NAME}" | sort --version-sort --field-separator='|' --key=1,1`"

	#-- DRIVES ONLY - $PROBEDISK
	elif [ "$HOTPLUGON" = "true" -a "$ICONDESK" = "true" ] ; then
		# $PROBEDISK already known - was set in frontend_startup/change
		DRV_SIZE=$(($DRV_SIZE/2)) # kb = /proc/partitions
		DRVINFO="$DRV_NAME|0|$DRV_SIZE|$DRV_DESCRIPTION"

	#-- only show a single 'drives' icon on desktop...
	else
		DRV_NAME='drives'
		DRV_CATEGORY='any' #see pmount.
		DRV_DESCRIPTION="all drives"
		DRVINFO="$DRV_NAME"'|0|0'
	fi
	#--

	while IFS="|" read ONEDRVNAME FSTYPE SIZE DRV_LABEL zz
	do
		ONEDRVNAME=${ONEDRVNAME##*/} #basename
		if [ "$ICONPARTITIONS" = "true" ] ; then
			case "${ONEDRVNAME}" in
				sr*) ok=1 ;;
				*) case "$FSTYPE" in swap|none) continue ;; esac ;;
			esac
		fi
		if [ ! -e /tmp/pup_event_frontend/drive_${ONEDRVNAME} ];then
			drive_all_frontend ${ONEDRVNAME}
			if [ "$FSTYPE" = "0" -a "$SIZE" = "0" ];then
				INFO="$(gettext 'Puppy drive manager')"
			elif [ "$ICONPARTITIONS" = "true" ] ; then
				SIZE=$( fx_format_bytes $(($SIZE * 1024)) ) # formats SIZE for display
				INFO="$(gettext 'Filesystem'): ${FSTYPE} $(gettext 'Size'): ${SIZE}  [${DRV_DESCRIPTION}]" #*WARNING* parsed in clean_desk_icons !!!
			elif [ "$ICONDESK" = "true" ] ; then
				SIZE=$( fx_format_bytes $(($SIZE * 1024)) ) # formats SIZE for display
				INFO="$(gettext 'Size'): ${SIZE}  [${DRV_DESCRIPTION}]"
			fi
			#v424 add item to unmount all partitions...
			MOREITEMS="<Item option=\"unmount\" icon=\"gtk-harddisk\"><Label>$(eval_gettext 'Unmount ${ONEDRVNAME} [if currently mounted]')</Label></Item><Item option=\"unmountall\" icon=\"gtk-harddisk\"><Label>$(gettext 'Unmount ALL mounted partitions')</Label></Item>"
			rox_create_appinfo_func #needs INFO, DRV_CATEGORY, MOREITEMS, ONEDRVNAME
		fi
		MNTSTATUS="$(mount -v | grep -E "^/dev/${ONEDRVNAME} |^/dev/mapper/lukspartition_${ONEDRVNAME} ")"
		if [ "$MNTSTATUS" = "" ];then
			rox_icon_unmounted_func "$ONEDRVNAME" "$DRV_CATEGORY" "$FSTYPE"
		else
			rox_icon_mounted_func "$ONEDRVNAME" "$DRV_CATEGORY" "$FSTYPE"
		fi
		rox_add_pinboard_func #needs ONEDRVNAME, DRV_CATEGORY, FSTYPE.
	done <<EOF
$DRVINFO
EOF
	#-
	#always create a handler for entire drive, even if no icon displayed...
	if [ ! -e /tmp/pup_event_frontend/drive_${DRV_NAME} ];then
		if [ -e /sys/block/${DRV_NAME} ];then
			drive_all_frontend ${DRV_NAME}
			if [ -e /sys/block/${DRV_NAME}/size ];then
				read -r SIZE < /sys/block/${DRV_NAME}/size
				SIZE=$(($SIZE/2)) #get KB.
			fi
			SIZE=$( fx_format_bytes $(($SIZE * 1024)) ) # formats SIZE for display
			INFO="$(gettext 'Description'): ${DRV_DESCRIPTION} $(gettext 'Size'): ${SIZE}"
			#v424 add item to unmount all mounted partitions...
			MOREITEMS="</Item><Item option=\"unmountall\" icon=\"gtk-harddisk\"><Label>$(gettext 'Unmount ALL mounted partitions')</Label></Item>"
			ONEDRVNAME="$DRV_NAME"
			rox_create_appinfo_func #needs INFO, DRV_CATEGORY, MOREITEMS, ONEDRVNAME
		fi
	fi
}

# $1: DRV_NAME
rox_remove_pinboard_func() {
	[ "$ROX_DESKTOP" != "yes" ] && return
	local DRV_NAME="$1"
	DRV_NAME=$(fx_get_drvname $DRV_NAME)
	rpPTN="drive_${DRV_NAME}[^<]*" #130610 label may differ from drv name.
	[ "`grep "$rpPTN" /root/Choices/ROX-Filer/PuppyPin`" = "" ] && return
	ALLNAMES="`grep -o "$rpPTN" /root/Choices/ROX-Filer/PuppyPin | cut -f 2 -d '_' | cut -f 1 -d '<' | tr '\n' ' '`"
	for ONEDRVNAME in $ALLNAMES
	do
		echo "<?xml version=\"1.0\"?>
<env:Envelope xmlns:env=\"http://www.w3.org/2001/12/soap-envelope\">
 <env:Body xmlns=\"http://rox.sourceforge.net/SOAP/ROX-Filer\">
  <PinboardRemove>
   <Path>/tmp/pup_event_frontend/drive_${ONEDRVNAME}</Path>
  </PinboardRemove>
 </env:Body>
</env:Envelope>"  | roxfiler_R
	done
}


#==================================================================
#                     mount / umount
#==================================================================

rox_mount() {
	[ "$ROX_DESKTOP" != "yes" ] && return
	[ ! "$DISPLAY" ] && export DISPLAY=:0
	DEVNAME="`busybox mount | tail -n 1 | grep '^/dev/' | cut -f 1 -d ' ' | cut -f 3 -d '/'`"
	if [ "$DEVNAME" != "" ];then
		DRVNAME=$(fx_get_drvname $DEVNAME)
		xDRVNAME="$DRVNAME" #v404
		[ -e /tmp/pup_event_frontend/drive_${DEVNAME} ] && DRVNAME="$DEVNAME" #icon for each partition.
		if [ -e /tmp/pup_event_frontend/drive_${DRVNAME} ];then
			DRV_CATEGORY="`probedisk /dev/${xDRVNAME} | cut -f 2 -d '|'`"
			rox_icon_mounted_func $DRVNAME $DRV_CATEGORY #see frontend_funcs
		fi
	fi
}

# $@: all params passed to /bin/umount
#     refresh desktop icon
rox_umount() {
	if [ "$ROX_DESKTOP" != "yes" ] ; then
		umount-FULL -d "$@"
		return $?
	fi
	if [ ! "$DISPLAY" ] ; then
		export DISPLAY=:0
	fi
	#===
	#remove everything except the device or mntpt...
	LASTPARAM="`echo -n "$@" | tr '\t' ' ' | tr -s ' ' | tr ' ' '\n' | grep '^/'`"
	MNTPT=
	if [ "$LASTPARAM" != "" ] ; then
		if [ -b "$1" ] ; then
			# block device
			DEVNAME=$(basename "$LASTPARAM")
			MNTPT=$(mount-FULL -v | grep "^$LASTPARAM " | cut -f 3 -d " ")
		else
			# mountpoint
			DEVNAME=$(mount-FULL -v | grep " $LASTPARAM " | cut -f 1 -d " ")
			DEVNAME=$(basename "$DEVNAME")
			MNTPT=$LASTPARAM
		fi
	fi
	#-
	umount-FULL -d "$@"
	RETVAL=$?
	#-
	if [ "${MNTPT}" ] && [ ! "`mount | grep -q " ${MNTPT} "`" ] ; then
		rox -D "${MNTPT}" #not mounted, close rox window
	fi
	#-
	if [ -z "$DEVNAME" -o ! -b /dev/${DEVNAME} ] ; then
		return $RETVAL
	fi
	#-
	DRVNAME=$(fx_get_drvname $DEVNAME)
	DRV_CATEGORY="`probedisk /dev/${DRVNAME} | cut -f 2 -d '|'`"
	[ -e /tmp/pup_event_frontend/drive_${DEVNAME} ] && DRVNAME="$DEVNAME" #icon for each partition. ex: DRVNAME=sda1
	if [ -e /tmp/pup_event_frontend/drive_${DRVNAME} ];then
		#if any partitions still mounted, leave "MNTD" on icon...
		drvPATTERN='^/dev/'"${DRVNAME} "
		#"MNTD" text is intended as a reminder to user that drive needs to be unmounted,
		#   but partitions in use by Puppy cannot be unmounted.
		if [ "`mount-FULL -v | tr -s ' ' | cut -f 1,3 -d ' ' | grep "$drvPATTERN" | grep -v ' /initrd/' | grep -v ' /$'`" = "" ];then
			if [ "`mount-FULL -v | tr -s ' ' | cut -f 1,3 -d ' ' | grep "$drvPATTERN" | grep -E ' /initrd/| /$'`" != "" ];then
				#only a partition left mntd that is in use by puppy, change green->yellow...
				rox_icon_mounted_func $DRVNAME $DRV_CATEGORY #see frontend_funcs
			else
				#redraw icon without "MNTD" text...
				rox_icon_unmounted_func $DRVNAME $DRV_CATEGORY #see frontend_funcs
			fi
		fi
	fi
	return $RETVAL
}

rox_mount_luks() {
	[ "$ROX_DESKTOP" != "yes" ] && return
	[ ! "$DISPLAY" ] && export DISPLAY=:0
	DEVNAME="`busybox mount | tail -n 1 | grep '^/dev/' | cut -f 1 -d ' '`"
	DEVNAME=${DEVNAME##*/}            # basename $DEVNAME
	DEVNAME=${DEVNAME#lukspartition_} # remove lukspartition_ (ex: lukspartition_sdb1)
	if [ "$DEVNAME" != "" ];then
		DRVNAME=$(fx_get_drvname $DEVNAME)
		xDRVNAME="$DRVNAME" #v404
		[ -e /tmp/pup_event_frontend/drive_${DEVNAME} ] && DRVNAME="$DEVNAME" #icon for each partition.
		if [ -e /tmp/pup_event_frontend/drive_${DRVNAME} ];then
			DRV_CATEGORY="`probedisk "/dev/${xDRVNAME} " | cut -f 2 -d '|'`"
			rox_icon_mounted_func $DRVNAME $DRV_CATEGORY crypto_LUKS #see frontend_funcs
		fi
	fi
}

rox_umount_luks() {
	[ "$ROX_DESKTOP" != "yes" ] && return
	[ ! "$DISPLAY" ] && export DISPLAY=:0
	DEVNAME="$1"
	DRVNAME=$(fx_get_drvname $DEVNAME)
	DRV_CATEGORY="`probedisk /dev/${DRVNAME} | cut -f 2 -d '|'`"
	[ -e /tmp/pup_event_frontend/drive_${DEVNAME} ] && DRVNAME="$DEVNAME" #icon for each partition. ex: DRVNAME=sda1
	if [ -e /tmp/pup_event_frontend/drive_${DRVNAME} ];then
		#if any partitions still mounted, leave "MNTD" on icon...
		drvPATTERN='^/dev/'"${DRVNAME} "
		#"MNTD" text is intended as a reminder to user that drive needs to be unmounted,
		#   but partitions in use by Puppy cannot be unmounted.
		if [ "`mount-FULL -v | tr -s ' ' | cut -f 1,3 -d ' ' | grep "$drvPATTERN" | grep -v ' /initrd/' | grep -v ' /$'`" = "" ];then
			if [ "`mount-FULL -v | tr -s ' ' | cut -f 1,3 -d ' ' | grep "$drvPATTERN" | grep -E ' /initrd/| /$'`" != "" ];then
				#only a partition left mntd that is in use by puppy, change green->yellow...
				rox_icon_mounted_func $DRVNAME $DRV_CATEGORY crypto_LUKS
			else
				#redraw icon without "MNTD" text...
				rox_icon_unmounted_func $DRVNAME $DRV_CATEGORY crypto_LUKS
			fi
		fi
	fi
}




#===================================================================
#            DRIVE_ALL (see /usr/local/pup_event/drive_all)
#===================================================================

unmount_func() {
	sync
	while [ 1 ]
	do
		umount.crypto_LUKS "$MNTPT" || umount "$MNTPT"
		umVAL=$?
		#fix zombie process prevents partition unmount, invisible to fuser...
		if [ $umVAL -ne 0 ];then
			#120129 karl godt: fix ZOMBIES, see http://murga-linux.com/puppy/viewtopic.php?t=71767&start=420 ...
			ZOMBIES="`ps -H -A | grep '<defunct>' | sed 's/^[[:blank:]]*//;s/  /|/g' | grep -v '|||' | cut -f 1 -d ' ' | tr '\n' ' '`"
			for ONEZOMBIE in $ZOMBIES
			do
				echo "Killing parentless zombie process $ONEZOMBIE"
				kill $ONEZOMBIE
			done
			umount $MNTPT ; umVAL=$?
		fi
		#rare ocassion, partition got unmounted before umount runs above...
		mount | grep -q " ${MNTPT} " || {
			umVAL=0 #not mounted
		}
		if [ $umVAL -ne 0 ];then
			EXTRAMSG0="`fuser -v -m $MNTPT`"  
			if [ "$EXTRAMSG0" = "" ];then
				/usr/lib/gtkdialog/box_ok "$(gettext 'Puppy drive manager')" error  "$(gettext 'FAILURE! In the case of removable media, the most
common reason is the media is not currently inserted.
If so, please remedy.')"
			else
				xmessage -bg "#ff99ff" -title "$(gettext 'Puppy drive manager: FAIL')" -center -buttons "$(gettext 'KILL')":10,"$(gettext 'EXIT')":20 "$(gettext 'FAILURE!')
$(gettext 'One or more processes (programs) are currently
using the partition. Here they are:')
${EXTRAMSG0}

$(gettext "If you press the 'KILL' button, Puppy will attempt to
kill the offending programs for you. Only do this as a
last resort.")
$(gettext "Firstly you should try to close the programs
manually, so do not press 'KILL'.")
$(gettext "PLEASE PRESS THE 'EXIT' BUTTON!")"
				if [ $? -eq 10 ];then
					fuser -k -m $MNTPT
					continue
				fi
			fi
		else
			[ "$DRV_CATEGORY" = "optical" ]  && eject /dev/$ONEDRVNAME
		fi
		break
	done
}

#
# drive_all
#
rox_desktop_icon_clicked() {
	[ "$ROX_DESKTOP" != "yes" ] && return
	ONEDRVNAME="$1" # /tmp/pup_event_frontend/drive_<ONEDRVNAME>/AppRun
	PARAM1="$2"
	FSTYPE="$3"
	#--------------------------------------------------------------------
	#   detect if have clicked on a close-box of mounted partition...
	#--------------------------------------------------------------------
	#when left-click desktop icon, param1 passed this script: drive|card|floppy|optical|usbdrv
	# and param2 has the fs type...
	case $PARAM1 in drive|card|floppy|optical|usbdrv)
	  MNTPT="`mount | grep -m1 -E "^/dev/${ONEDRVNAME} |^/dev/mapper/lukspartition_${ONEDRVNAME} " | tr -s ' ' | cut -f 3 -d ' '`"
	  if [ "$MNTPT" ];then
	   read CURPOSX CURPOSY <<< `getcurpos`
	   #get coords of desktop icon...
	   drPTN=">/tmp/pup_event_frontend/drive_${ONEDRVNAME}<"
	   PPENTRY="`grep "$drPTN" /root/Choices/ROX-Filer/PuppyPin`"
	   if [ "$PPENTRY" ];then
		xleft="`echo -n "$PPENTRY" | grep -o ' x="[0-9]*"' | cut -f 2 -d '"'`" #'geany
		ytop="`echo -n "$PPENTRY" | grep -o ' y="[0-9]*"' | cut -f 2 -d '"'`" #'geany
		#hmmm, have to apply correction to cursor position...
		CURPOSX=$(($CURPOSX + 24))
		CURPOSY=$(($CURPOSY + 32))
		xcloseleft=$(($xleft + 35)) #close-box is 13x13 pixels, want bigger pickup area.
		xcloseright=$(($xleft + 53))
		yclosetop=$(($ytop - 5))
		yclosebottom=$(($ytop + 13))
		if [ $CURPOSX -ge $xcloseleft ];then
		 if [ $CURPOSX -le $xcloseright ];then
		  if [ $CURPOSY -ge $yclosetop ];then
		   if [ $CURPOSY -le $yclosebottom ];then
		    PARAM1="unmount"
		   fi
		  fi
		 fi
		fi
	   fi
	  fi
	 ;;
	esac

	# rox right-clik menu items...
	case "${PARAM1}" in
		unmount)
			# "Unmount drive [if currently mounted]"
			MNTPT="`mount | grep -m1 -E "^/dev/${ONEDRVNAME} |^/dev/mapper/lukspartition_${ONEDRVNAME} " | tr -s ' ' | cut -f 3 -d ' '`"
			if [ -e /sys/block/${ONEDRVNAME}  ] ; then
				DRV_CATEGORY=$(probedisk $ONEDRVNAME | cut -d'|' -f 2)
				[ "$MNTPT" = "" -a "$DRV_CATEGORY" = "optical" ] && eject /dev/$ONEDRVNAME
			fi
			[ "$MNTPT" = "" ] && exit #precaution.
			if [ "$MNTPT" = "/" -o "`echo "$MNTPT" | grep '/initrd/'`" != "" ];then
				/usr/lib/gtkdialog/box_ok "$(gettext 'Puppy drive manager')" error  "$(eval_gettext "/dev/\${ONEDRVNAME} mounted on \${MNTPT}
is in use by Puppy. You cannot unmount it.")"
				exit
			fi
			unmount_func
			exit
			;;
		pmount_*)
			# "Run Pmount Puppy Drive Mounter"
			DRV_CATEGORY="`echo -n "${PARAM1}" | cut -f 2 -d '_'`"
			if [ "`pidof gtkdialog_pmount`" != "" ];then #if pmount running, kill it.
				killall gtkdialog_pmount 2>/dev/null
				sleep 0.1
			fi
			exec pmount $ONEDRVNAME
			exit
			;;
		unmountall)
			# "Unmount ALL mounted partitions"
			for MNTPT in `mount | grep '^/dev/' | grep -vE '^/dev/loop|^/dev/ram' | cut -f 3 -d ' ' | grep -v '^/initrd/' | grep -v '^/$' | tr '\n' ' '`
			do
				unmount_func
			done
			exit
			;;
		eventmanager)
			# "Run Desktop Drive Icon Manager"
			exec eventmanager desktop
			exit
			;;
	esac

	#see /etc/eventmanager
	# ICONPARTITIONS=false - ICONDESK=false
	if [ "$ONEDRVNAME" = "drives" ];then
		if [ "`pidof gtkdialog_pmount`" != "" ];then #if pmount running, kill it.
			killall gtkdialog_pmount 2>/dev/null
			sleep 0.1
		fi
		exec pmount
	fi
}

#===================================================================

if [ "$1" ] ; then
	$@
fi

### END ###